<script lang="ts" setup>
  import type { FormInstance } from 'element-plus'
  import { Search, Refresh, Download } from '@element-plus/icons-vue'
  import { fetchDeptList } from '@/api/departmentManagement'
  import { deptStatistics } from '@/api/assetManagement'
  import { export_json_to_excel } from '@/utils/excel'
  import dayjs from 'dayjs'
  interface Dept {
    id: number
    name: string
    parentId: number
    status: number
    sort: number
    createTime: string
    updateTime: string
    children?: Dept[]
  }
  const ruleFormRef = ref<FormInstance>()
  const $baseMessage: any = inject('$baseMessage')
  const deptProps = {
    children: 'children',
    label: 'name',
  }
  const deptTreeData: Dept[] = ref([])
  const deptDefaultExpandedKeys = ref([])
  const tableData = ref([])
  const queryForm = reactive({
    deptId: null,
    date: [],
    beginDate: '',
    endDate: '',
    minPrice: null,
    maxPrice: null,
  })

  const getStartTime = () => {
    const start_time = new Date()
    start_time.setHours(0)
    start_time.setMinutes(0)
    start_time.setSeconds(0)
    return start_time
  }

  const getEndTime = () => {
    const end_time = new Date()
    end_time.setHours(23)
    end_time.setMinutes(59)
    end_time.setSeconds(59)
    return end_time
  }

  const getStartMonth = (month) => {
    return dayjs()
      .subtract(month, 'month')
      .startOf('month')
      .format('YYYY-MM-DD HH:mm:ss') // 获取上个月第一天
  }

  const getEndMonth = (month) => {
    return dayjs()
      .subtract(month, 'month')
      .endOf('month')
      .format('YYYY-MM-DD HH:mm:ss') // 获取上个月最后一天
  }

  const shortcuts = [
    {
      text: '当天',
      value: () => {
        const start = getStartTime()
        const end = getEndTime()
        return [start, end]
      },
    },
    {
      text: '前一天',
      value: () => {
        if (queryForm.date.length) {
          const start = new Date(queryForm.date[0])
          const end = new Date(queryForm.date[1])
          start.setTime(start.getTime() - 3600 * 1000 * 24)
          end.setTime(end.getTime() - 3600 * 1000 * 24)
          return [start, end]
        } else {
          const start = getStartTime()
          const end = getEndTime()
          start.setTime(start.getTime() - 3600 * 1000 * 24)
          end.setTime(end.getTime() - 3600 * 1000 * 24)
          return [start, end]
        }
      },
    },
    {
      text: '后一天',
      value: () => {
        if (queryForm.date.length) {
          const start = new Date(queryForm.date[0])
          const end = new Date(queryForm.date[1])
          start.setTime(start.getTime() + 3600 * 1000 * 24)
          end.setTime(end.getTime() + 3600 * 1000 * 24)
          return [start, end]
        } else {
          const start = getStartTime()
          const end = getEndTime()
          start.setTime(start.getTime() + 3600 * 1000 * 24)
          end.setTime(end.getTime() + 3600 * 1000 * 24)
          return [start, end]
        }
      },
    },
    {
      text: '本月',
      value: () => {
        const start = getStartMonth(0)
        const end = getEndMonth(0)
        return [start, end]
      },
    },
    {
      text: '上月',
      value: () => {
        if (queryForm.date.length) {
          const start = dayjs(queryForm.date[0])
            .subtract(1, 'month')
            .format('YYYY-MM-DD HH:mm:ss')
          const end = dayjs(queryForm.date[1])
            .subtract(1, 'month')
            .format('YYYY-MM-DD HH:mm:ss')
          return [start, end]
        } else {
          const start = getStartMonth(1)
          const end = getEndMonth(1)
          return [start, end]
        }
      },
    },
    {
      text: '下月',
      value: () => {
        if (queryForm.date.length) {
          const start = dayjs(queryForm.date[0])
            .add(1, 'month')
            .format('YYYY-MM-DD HH:mm:ss')
          const end = dayjs(queryForm.date[1])
            .add(1, 'month')
            .format('YYYY-MM-DD HH:mm:ss')
          return [start, end]
        } else {
          const start = getStartMonth(-1)
          const end = getEndMonth(-1)
          return [start, end]
        }
      },
    },
  ]

  const getDeptTreeList = async () => {
    try {
      const { data } = await fetchDeptList()
      data &&
        data.map((item) => {
          deptDefaultExpandedKeys.value.push(item.id)
        })
      deptTreeData.value = data
    } catch (err) {
      console.error(err)
    }
  }

  watch(
    () => queryForm.date,
    (cur) => {
      if (cur && cur.length) {
        queryForm.beginDate = cur[0]
        queryForm.endDate = cur[1]
      } else {
        queryForm.beginDate = ''
        queryForm.endDate = ''
      }
    }
  )

  const fetchData = async () => {
    if (queryForm.minPrice && queryForm.maxPrice < queryForm.minPrice) {
      $baseMessage(
        '最大金额不能小于最小金额，请重新输入',
        'info',
        'vab-hey-message-info'
      )
      return
    }
    if (!queryForm.minPrice && queryForm.maxPrice) {
      $baseMessage('请输入最小金额', 'info', 'vab-hey-message-info')
      return
    }
    try {
      const { data } = await deptStatistics(queryForm)
      tableData.value = data
    } catch (err) {
      console.error(err)
    }
  }
  const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
    queryForm.minPrice = null
    queryForm.maxPrice = null
    queryForm.beginDate = ''
    queryForm.endDate = ''
    fetchData()
  }

  const handleNodeClick = (data: Dept) => {
    queryForm.deptId = data.id
    fetchData()
  }

  const exportData = []
  const Loop = (data) => {
    data &&
      data.map((item) => {
        exportData.push(item)
        if (item.children && item.children.length > 0) {
          Loop(item.children)
        }
      })
  }

  const handleDownload = () => {
    Loop(JSON.parse(JSON.stringify(tableData.value)))
    const tHeader = [
      '部门名称',
      '在用数量',
      '在用金额(元)',
      '空闲数量',
      '空闲金额(元)',
      '已损坏数量',
      '已损坏金额(元)',
      '总数量',
      '总金额(元)',
    ]
    const filterVal = [
      'deptName',
      'use',
      'usePrice',
      'idle',
      'idlePrice',
      'scrap',
      'scrapPrice',
      'total',
      'priceTotal',
    ]
    const data = formatJson(filterVal, exportData)
    export_json_to_excel({
      header: tHeader,
      data,
      filename: '资产部门统计',
      autoWidth: false,
      bookType: 'xlsx',
    })
  }

  const formatJson = (filterVal, jsonData) => {
    return jsonData.map((v) =>
      filterVal.map((j) => {
        return v[j]
      })
    )
  }

  getDeptTreeList()
  fetchData()
</script>

<template>
  <el-row :gutter="22">
    <el-col :span="4">
      <el-card shadow="never">
        <el-tree
          :data="deptTreeData"
          :default-expanded-keys="deptDefaultExpandedKeys"
          :props="deptProps"
          node-key="id"
          :expand-on-click-node="false"
          @node-click="handleNodeClick"
        />
      </el-card>
    </el-col>
    <el-col :span="18">
      <div class="toolbar">
        <el-form ref="ruleFormRef" inline :model="queryForm" @submit.prevent>
          <el-form-item label="金额">
            <el-input-number
              v-model="queryForm.minPrice"
              :min="0"
              :controls="false"
              placeholder="请输入最小金额"
            />
            &nbsp; - &nbsp;
            <el-input-number
              v-model="queryForm.maxPrice"
              :controls="false"
              placeholder="请输入最大金额"
            />
          </el-form-item>
          <el-form-item label="创建时间" prop="date">
            <el-date-picker
              v-model="queryForm.date"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              :shortcuts="shortcuts"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item>
            <el-button :icon="Search" type="primary" @click="fetchData">
              查询
            </el-button>
            <el-button :icon="Refresh" @click="resetForm(ruleFormRef)">
              重置
            </el-button>
            <el-button :icon="Download" @click="handleDownload">导出</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="table-container">
        <el-table :data="tableData" row-key="deptId" border default-expand-all>
          <el-table-column
            type="index"
            label="序号"
            width="60"
            header-align="center"
            align="center"
          />
          <el-table-column
            prop="deptName"
            label="部门名称"
            header-align="center"
            align="left"
          />
          <el-table-column
            prop="use"
            label="在用数量"
            header-align="center"
            align="center"
          />
          <el-table-column
            prop="usePrice"
            label="在用金额(元)"
            header-align="center"
            align="center"
          />
          <el-table-column
            prop="idle"
            label="空闲数量"
            header-align="center"
            align="center"
          />
          <el-table-column
            prop="idlePrice"
            label="空闲金额(元)"
            header-align="center"
            align="center"
          />
          <el-table-column
            prop="scrap"
            label="已损坏数量"
            header-align="center"
            align="center"
          />
          <el-table-column
            prop="scrapPrice"
            label="已损坏金额(元)"
            header-align="center"
            align="center"
          />
          <el-table-column
            prop="total"
            label="总数量"
            header-align="center"
            align="center"
          />
          <el-table-column
            prop="priceTotal"
            label="总金额(元)"
            header-align="center"
            align="center"
          />
        </el-table>
      </div>
    </el-col>
  </el-row>
</template>
